// 函数组件
import React, {useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { Input, Select, Space, Table, Modal, message } from 'antd';
import "../goods/css/GoodAudit.less"
import "../../../pages/css/public.less"
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import Audit from "../goods/child/audit/Audit"
import { ConfigProvider } from 'antd';
import zh_CN from 'antd/es/locale/zh_CN';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { updateStatus,delDelByIds,getBrandList, getChildrenList, getGoodsNum, getListFindByCon, getParentList } from "../../../api/lys"
import { number, use } from 'echarts';
import ReactDOM from 'react-dom';

import $ from 'jquery'

//表格接口
interface DataType {
  id?: number, // 序号
  brandName: string
  categoryName: string
  goodsBrandId: number
  goodsCategoryId: number
  goodsChildId: number
  goodsDesc: string
  goodsId: number
  goodsName: string
  goodsOnTime: string
  goodsPay: string
  goodsPost: string
  goodsPriceRange: string
  goodsRec: string
  goodsSell: string
  goodsSer: string
  goodsSernum: string
  goodsShopId: number
  goodsStatus: string
  goodsSupplieId: number,
  goodsTrail: string,
  goodsImg:string

}

interface AllGoods {
  id: number,
  brandName: string
  categoryName: string
  goodsBrandId: number
  goodsCategoryId: number
  goodsChildId: number
  goodsDesc: string
  goodsId: number
  goodsName: string
  goodsOnTime: string
  goodsPay: string
  goodsPost: string
  goodsPriceRange: string
  goodsRec: string
  goodsSell: string
  goodsSer: string
  goodsSernum: string
  goodsShopId: number
  goodsStatus: string
  goodsSupplieId: number,
  goodsTrail: string
}

interface parentType {
  categoryCreated: string
  categoryId: number
  categoryImg: string
  categoryMsg: string
  categoryName: string
  categoryNumbe: number
  categoryParent: number
  categoryRec: string
  categorySort: string
  categoryStatus: string
}

interface AuditType {
  id: number,
  title: string,
  number: number | undefined,
  isStyle: boolean
}

interface Obj {
  value: string,
  id: number,
  label: string
}

interface brandType {
  "brandId": number,
  "brandName": string,
  "brandLogo": string,
  "brandDesc": string,
  "brandCreated": string,
  "brandCategoryId": null
}

function GoodAudit() {
  const selRef = useRef(null)
  // const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  //商品数据
  const [data, setData] = useState<DataType[]>([])
  //checkBox选中ID值
  const [checkArr,setCheckArr] = useState<any[]>([])
  //分类-父类数据
  const [parentTable, setParentTable] = useState([])
  const [childrenTable, setChildrenTable] = useState([])
  //品牌数据
  const [brandTable, setBrandTable] = useState([])
  //页码数据
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [count, setCount] = useState<number>()
  const [count2, setCount2] = useState<number>()
  const [count3, setCount3] = useState<number>()
  const [count4, setCount4] = useState<number>()
  const [pageCount,setPageCount] = useState<number>()
    //筛选框收缩
  const [isShow, setIsShow] = useState<boolean>(true)
  //筛选框数据
  const [keyword, setKeyword] = useState<string>("")
  const [dustbin, setDustbin] = useState<number>()
  const [dustbin2, setDustbin2] = useState<string>("")
  const [brand, setBrand] = useState<string>()
 const [clearText,setClearText]=useState<boolean>(false)

  //审核弹框显隐藏状态
  const [isAudit, setIsAudit] = useState<boolean>(false)
  // 顶部 状态项  下标  
  const [isStyle, setIsStyle] = useState<number>(0)
  //model框显示隐藏状态
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  //查看按钮record数据
  const [checkAudit, setCheckAudit] = useState<any>()
  //单个审核点击项record数据
  const [checkAudit1, setCheckAudit1] = useState<any>()
  //审核  批量审核状态
  const [auditType, setAuditType] = useState<string>("")
  const [messageApi, contextHolder] = message.useMessage();
  //顶部  审核状态数据 
  //checkBox选中数据
  const [selectedRow, setSelectedRow] = useState<number[]>([]);
  
  //图片地址头
  const imgUrl="http://172.16.110.80:8080"

  const [arr, setArr] = useState<AuditType[]>([{
    id: 0,
    title: "全部商品",
    number: 5,
    isStyle: true,
  },
  {
    id: 1,
    title: "待审核",
    number: 1,
    isStyle: true,
  },
  {
    id: 2,
    title: "已审核",
    number: 2,
    isStyle: true,
  },
  {
    id: 3,
    title: "未通过",
    number: 2,
    isStyle: true,
  }])



  const [sort, setSort] = useState([
    { id: 1, value: 'goods_price_range!1' ,label:"按价格顺序"},
    { id: 2, value: 'goods_price_range!2',label:"按价格倒序" },
    { id: 3, value: 'goods_sell!1',label:"按销量顺序" },
    { id: 4, value: 'goods_sell!2' ,label:"按销量倒序"},
    { id: 5, value: 'goods_ontime!1',label:"按上架时间顺序" },
    { id: 6, value: 'goods_ontime!2',label:"按上架时间倒序" },
  ])


  //表格数据渲染
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'goodsId',
      width: "7%"
    },
    {
      title: '商品图片',
      width: "12%",
      dataIndex: 'goodsImg',
      render: (_, record) => (
        <Space size="middle">
          <img width={50} height={50} 
          src={imgUrl+"/Pic/c648d90a4f094253bfa3ceeb7fcdc62d.jpg"} 
          alt="" />
        </Space>
      )
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      width: "8%",
    },
    {
      title: '货号',
      width: "10%",
      dataIndex: 'goodsSernum',
    },
    {
      title: '价格',
      width: "12%",
      dataIndex: 'goodsPriceRange',
    },
    {
      title: '分类',
      width: "12%",
      dataIndex: 'categoryName',
    },
    {
      title: '品牌',
      width: "8%",
      dataIndex: 'brandName',
    },
    {
      title: '状态',
      width: "8%",
      dataIndex: 'goodsTrail',
    },
    {
      title: '操作',
      dataIndex: 'shop_handle',
      render: (_, record) => (
        <div>
          <button className=' add1' onClick={() => tableAudit(record)}>审核</button>
          <button className='edit' onClick={() => showModal(record)}>查看</button>
          <button className='del' onClick={() => delAudit(record)}>删除</button>
        </div>
      )
    },
  ];

  const [status,setStatus] = useState<string>()

  useEffect(() => {
    goodsList(page, pageSize,status)
  }, [page, pageSize])



  useEffect(() => {
    getParentLists()
    getBrandLists()
    getGoodsNums(0, setCount2)
    getGoodsNums(1, setCount3)
    getGoodsNums(2, setCount4)
  }, [])

//获取商品数据
  const goodsList = (pages: number | undefined, pageSizes: number | undefined, goodsTrail?: string) => {
    getListFindByCon({
      "limit": pageSizes,
      "page": pages,
      "goodsTrail": goodsTrail
    }).then((res) => {
      console.log("请求的数据", res);

      if (res.code == "200") {
        // let list = filterData(res.data.data)
        
        setData(res.data.data)
        // setData(list)
        addKey(res.data.data)
        if(status == ''){
            setCount(res.data.totalByStatus)
        }
      }
    })
  }

//排序

const sortGoods = (name:string,orderNum: string,)=>{
      getListFindByCon({
      "limit": pageSize,
      "name": name,
      "orderNum":orderNum,
      "page": page
    }).then((res)=>{
      if (res.code == "200") {
        messageApi.open({
          type: 'success',
          content: '排序成功',
        });
        setData(res.data.data)
        addKey(res.data.data)
        setCount(res.data.totalByStatus)
      }
    })
}

  // // 过滤删除的数据
  // function filterData(data:any){
  //   let list = data.filter((item:any)=>{
  //      return item.goodsStatus!='6'
  //   })
  //   console.log("list",list);

  //   return list
  // }
  
  //获取品牌数据
  const getBrandLists = () => {
    getBrandList().then((res) => {
      if (String(res.code) === "200") {
        let parentArr: any = []
        res.data.map((item) => {
          let obj2: Obj = {
            value: item.brandName,
            id: item.brandId,
            label: item.brandName
          }
          parentArr.push(obj2)
        })

        setBrandTable(parentArr)

        messageApi.open({
          type: 'success',
          content: '获取成功',
        });
      }
    })
  }

  //获取状态下的数量
  const getGoodsNums = (id: number, setList: any) => {
    getGoodsNum({ "status": id }).then((res) => {
      // console.log("状态下的数量res", res);
      setList(res.data)
    })
  }


  //获取商品分类父类数据
  const getParentLists = () => {
    getParentList().then((res) => {
      if (String(res.code) === "200") {
        let parentArr: any = []
        res.data.map((item) => {
          let obj2: Obj = {
            value: item.categoryName,
            id: item.categoryId,
            label: item.categoryName
          }
          parentArr.push(obj2)
        })

        setParentTable(parentArr)
      }
    })
  }


  const rowSelection = {
    onChange:(key :any,row :DataType[])=>{
   
      let checkArr:any=[];
      row.map(item=>{
        checkArr.push(item.goodsId)
      })
      setSelectedRow(checkArr)
      console.log("checkArr",checkArr);
    },
  }



  //顶部点击按钮高亮
  const clickStyle = (e: any, i: any) => {
    console.log("event", e.target.dataset.index);
    console.log("arr[i]", i);
    setIsStyle(parseInt(e.target.dataset.index, 10))
    if (i.id === 0) {
      console.log("点击了全部商品，发起请求");
      goodsList(page, pageSize)
    }
    //待审核
    if (i.id === 1) {
      console.log("点击了待审核，发起请求");
      setStatus('0')
      getListFindByCon({
        "limit": pageSize,
        "page": page,
        "goodsTrail": "0",
      }).then((res) => {
        console.log("全部待审核数据", res);
        if (res.code == "200") {
          setData(res.data.data)
          addKey(res.data.data)
          setCount(count2)
        }
      })


    }

    //已通过
    if (i.id === 2) {
      console.log("点击了已审核，发起请求");
      setStatus('1')
      getListFindByCon({
        "limit": pageSize,
        "page": page,
        "goodsTrail": "1",
      }).then((res) => {
        console.log("全部已审核数据", res);
        if (res.code == "200") {
          setData(res.data.data)
          addKey(res.data.data)
          setCount(count3)
        }
      })
    }
    //未通过
    if (i.id === 3) {
      console.log("点击了未通过，发起请求");
      setStatus('2')
      getListFindByCon({
        "limit": pageSize,
        "page": page,
        "goodsTrail": "2",
      }).then((res) => {
        console.log("全部商品数据", res);
        if (res.code == "200") {
          setData(res.data.data)
          addKey(res.data.data)
          setCount(count4)
        }
      })

    }

  }

  //顶部 全部商品 待审核  已通过  未通过   结构渲染
  let itemList = []
  for (let i = 0; i < arr.length; i++) {
    itemList.push(<p
      className={isStyle === i ? "colorStyle" : ""}
      key={arr[i].id}
      data-index={i}
      onClick={() => clickStyle(event, arr[i])}>
      {arr[i].title}
      (<span className={isStyle === i ? "colorStyle" : "spanColor"}
      >{arr[i].id==0?count:arr[i].id==1?count2:arr[i].id==2?count3:arr[i].id==3?count4:""}</span>)
    </p>)
  }

  //筛选
  const clickFilter = () => {
    let obj = {
      "goodsName": keyword,//名称
      "goodsCategoryId": dustbin,//类别
      "brandName": brand,//品牌
      "goodsTrail": `${dustbin2 == "待审核" ? "0" : dustbin2 == "已审核" ? "1" : "2"}`,//状态
      "limit": pageSize,
      "page": page
    }
    getListFindByCon(obj).then((res) => {
      console.log("筛选res", res);
     if(res.code=="200"){
      setData(res.data.data)
      addKey(res.data.data)
      setCount(res.data.data.length)
      messageApi.open({
        type: 'success',
        content: '筛选成功',
      });
     }
    }).catch((err) => {
      if (err.code == "500") {
        messageApi.open({
          type: 'error',
          content: '不存在该商品',
        });
      }
    })
  }

  //重置
  const clickReset = () => {
    console.log("22222222",$('.ant-select-clear'));
    
    setKeyword("")
    $('.ant-select-clear').trigger('click')
    $('.ant-input-clear-icon').trigger('click')
    setClearText(true)
  }

  //单个查看按钮
  const showModal = (record: any) => {
    setIsModalOpen(true);
    console.log("record", record);
    setCheckAudit(record);
  };

  //model框确认按钮
  const handleOk = () => {
    setIsModalOpen(false);
  };

  //关闭model框
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //单个审核
  const tableAudit = (record: any) => {
    setIsAudit(true)
    setCheckAudit1(record)
    setAuditType("审核")
    console.log("record",record);
    
  }

  const allAudits = ()=>{

    if (selectedRow.length) {
          setIsAudit(true); 
          setAuditType("批量审核")
    } else {
      messageApi.open({
        type: 'warning',
        content: '请至少选择一个',
      });
    }
    
  
  }


  const { confirm } = Modal;
  //批量删除
  const showConfirm = () => {

    if (selectedRow.length) {
      confirm({
        centered: true,
        cancelText: "取消",
        okText: "确定",
        title: '是否全部删除',
        icon: <ExclamationCircleFilled />,
        content: '删除选中项，一项或多项',
        onOk() {
          updateStatu({ 
          "ids": selectedRow,
          "status": "6"
        })
          console.log('OK');
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    } else {
      console.log('请至少选择一个');
      messageApi.open({
        type: 'warning',
        content: '请至少选择一个',
      });
    }

  };

  const updateStatu = (obj:any) => {
    updateStatus(obj).then((res) => {
      console.log("res11111111", res);
      if(res.code=="200"){
        messageApi.open({
          type: 'success',
          content: '删除成功',
        });
        console.log("删除成功");
        goodsList(page,pageSize)
      }
    }).catch((err)=>{
      messageApi.open({
        type: 'error',
        content: '删除失败',
      });
      console.log("出错了");
    })
}


  //单个删除
  const delAudit = (record: any) => {
    let arrs:number[] = []
    arrs.push(record.goodsId)
    confirm({
      centered: true,
      cancelText: "取消",
      okText: "确定",
      title: '是否删除选中项',
      icon: <ExclamationCircleFilled />,
      content: '',
      onOk() {
        updateStatu({ 
          "ids": arrs,
        "status": "6"
      })

        console.log("arrs",arrs);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  //按是否上架搜索内容
  const handleChange2 = (value: string) => {
    console.log(`按是否上架搜索 ${value}`);
      let string2 = value.split("!")
      console.log("string2",string2);
    sortGoods(string2[0],string2[1])
  };

  const onChangePage = (page: any, pageSize: any) => {
    console.log("页码", page, pageSize);
    setPage(page)
    setPageSize(pageSize)
  }


 

  const addKey = (data: any) => {
    data.map((item: AllGoods) => {
      item.id = Math.floor(Math.random() * 10000000000)
      return item
    })
  }

  //一级分类
  const parentChange = (id: number, value: any) => {
    console.log("value", value);
    setDustbin(value.id)
    getChildrenList({ id: value.id }).then((res) => {
      console.log("res", res);
      let parentArr: any = []
      res.data.map((item) => {
        let obj2: Obj = {
          value: item.categoryName,
          id: item.categoryId,
          label: item.categoryName
        }
        parentArr.push(obj2)
      })

      setChildrenTable(parentArr)
      // console.log("一级分类", childrenTable);

    })

  }
  //品牌筛选

  return (
    <div className='GoodAudit'>
      {contextHolder}
      {/* 审核弹框 */}
      {isAudit ? <Audit selectedRow={selectedRow} page={page} pageSize={pageSize} auditType={auditType} checkAudit1={checkAudit1} isAudit={setIsAudit} goodsList={goodsList}></Audit> : ""}

      {/* 头部标题 */}
      <div className='page-top'>
        <div className='page-title'>
          <p>商品审核</p>
        </div>
      </div>


      <div className='page-context'>
        {/* 商品审核状态 */}
        <div className='aduit-state'>
          <div className='aduit-state-left'>
            {itemList}
          </div>
        </div>


        {/* 筛选框 */}
        <div className='search-input'>

          <div style={{ display: 'flex', justifyContent: 'space-between', height: "50px" }}>
            <p>商品筛选</p>
            {isShow ? <UpOutlined onClick={() => {
              setIsShow(false)
            }} /> : <DownOutlined onClick={() => {
              setIsShow(true)
            }} />}
          </div>
          {isShow ?
            <div style={{ height: "180px" }}>
              <div className='header-top'>

                {/* 关键词 */}
                <div>
                  <span>关键词</span><Input value={keyword} onChange={(e: any) => {
                    setKeyword(e.target.value)
                    // console.log("关键词", e.target.value);
                  }} placeholder="商品名称/商品货号" />
                </div>

                {/* 分类 */}
                <div>
                  <span>分类</span>
                  <div>
                    <Select ref={selRef} allowClear placeholder="一级分类"
                      style={{ width: 120 }}
                      onChange={parentChange}
                      options={parentTable} />~
                    <Select allowClear placeholder="二级分类"
                      style={{ width: 120 }}
                      onChange={(value: string) => {
                        // console.log("二级分类", value);
                      }}
                      options={childrenTable} />
                  </div>
                </div>

                {/* 状态 */}
                <div>
                  <span>状态</span>
                  <div> <Select  allowClear autoClearSearchValue={false} placeholder="请选择状态"
                    style={{ width: 120 }}
                    onChange={(value: string) => {

                      // console.log("状态：", value);
                      setDustbin2(value)
                    }}
                    options={[
                      { value: '待审核', label: '待审核' },
                      { value: '已审核', label: '已审核' },
                      { value: '未通过', label: '未通过' },

                    ]}
                    autoFocus={false} />
                  </div>

                </div>

                {/* 品牌 */}
                <div>
                  <span>品牌</span>
                  <div> <Select allowClear placeholder="请选择品牌"
                    style={{ width: 120 }}
                    onChange={(value: string) => {
                      // console.log("品牌：", value);
                      setBrand(value)
                    }}
                    options={brandTable}
                    autoFocus={false} />
                  </div>

                </div>

              </div>

              <div className='button-box'><button className='reset' onClick={clickReset}>重置</button><button className='screen' onClick={clickFilter}>筛选</button></div>

            </div> : ""}
        </div>

        {/* 表格 */}
        <div className='data-list'>
          <div>
            <p>数据列表</p>
            <div className='data-list-method'>
              <div>
                <span style={{ marginRight: "15px" }}>排序方式</span>
                <Select
                  dropdownStyle={{ width: '120px' }}
                  className='Select1'
                  defaultValue="排序方式"
                  onChange={handleChange2}
                  options={sort}

                />
              </div>
              <button className='batch-del' onClick={showConfirm}>批量删除</button>
              <button className='add' onClick={allAudits}>批量审核</button>
            </div>
          </div>
          {/* 表格 */}
          <div className='table-box'>
            <ConfigProvider locale={zh_CN}>
              <Table rowSelection={rowSelection} columns={columns} dataSource={data}
                scroll={{ y: 444 }}
                rowKey={item => String(item.id)}
                // rowKey={item =>item.goodsId}
                pagination={{
                  position: ['bottomCenter'],
                  total: count,
                  defaultPageSize: 3,
                  pageSizeOptions: [3, 5, 10, 15],
                  showQuickJumper: true,
                  showSizeChanger: true,
                  onChange: onChangePage
                }}
              />
            </ConfigProvider>
          </div>
          <Modal forceRender centered={true} title="查看详情" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
            <div>
              <img width={200} height={200} src={imgUrl+"/Pic/c648d90a4f094253bfa3ceeb7fcdc62d.jpg"} alt="" />
              <h3>{checkAudit?.goodsName}</h3>
              <div style={{ display: 'flex', alignItems: "center", justifyContent: "space-between", width: "40%" }}>
                <div>
                  <span style={{ fontSize: "20px" }}>￥</span>
                  <span style={{ fontSize: "28px", color: "red", marginRight: "20px" }}>{checkAudit?.goodsPriceRange}</span>
                </div>
                <span style={{ color: "green" }}>{checkAudit?.goodsTrail}</span>
              </div>
              <p style={{ fontSize: "16px" }}>品牌：{checkAudit?.brandName}</p>
              <p style={{ fontSize: "16px" }}>货号：{checkAudit?.goodsSernum}</p>
              <p style={{ fontSize: "16px" }}>类别：{checkAudit?.categoryName}</p>
            </div>
          </Modal>
        </div>
      </div>
    </div>
  )
}

export default GoodAudit